﻿using System;
using System.Linq;
using System.Web.Mvc;
using KLS.PPDS.ApplicationService.Manager;
using KLS.PPDS.Web.Models;
using KLS.PPDS.Utilities.BaseController;
using KLS.PPDS.Utility;
using KLS.PPDS.Utilities.Attributes;
using System.IO;
using KLS.PPDS.Utilities;
using System.Web;
namespace KLS.PPDS.Web.Controllers.Article
{
    /// <summary>
    /// Controller class for Article View
    /// </summary>
    public class ArticleController : BaseController
    {
        //
        // GET: /Article/
        /// <summary>
        /// Index action for article
        /// </summary>
        /// <param name="model"></param>
        ///  <param name="publicationId"></param>
        ///  <param name="articleId"></param>
        /// <param name="startPage"> article starting page</param>
        /// <returns></returns>
        [AjaxAuthorize(Roles = RoleConstant.All)]
        public ActionResult Index(ArticleViewModel model, int publicationId, int? articleId,int? startPage)
        {
            ArticleModel.ProcessIndex(model, publicationId, articleId.GetValueOrDefault(0),startPage.GetValueOrDefault(0));

            return View(model);
        }

         [AjaxAuthorize(Roles = RoleConstant.SuperadminOrEditor)]
        public ActionResult Delete(int publicationId, int articleId)
        {
            ArticleModel.DeleteArticle(articleId);
            return RedirectToAction("Index", "Article",
                                        new { @publicationId = publicationId, @articleId = "0" });
        }


        /// <summary>
        /// Save or update the article to the database
        /// </summary>
        /// <returns></returns>
        [AjaxAuthorize(Roles = RoleConstant.All)]
        public ActionResult SaveArticle(ArticleViewModel model)
        {
            var isReadyForEditor = Request.Form["Article.IsReadyForEditor"];
            var isReadyForGraphic = Request.Form["Article.IsReadyForGraphic"];
            

            if (isReadyForEditor != null || model.OldIsReadyForEditor)
            {
                model.Article.IsReadyForEditor = true;
            }

            if (isReadyForGraphic != null || model.OldIsReadyForGraphic)
            {
                model.Article.IsReadyForGraphic = true;
            }

            var s = ArticleModel.Save(model);
            if (String.IsNullOrEmpty(s))
            {
                var newModel = new ArticleViewModel();



                model.CopyPropertyValue<ArticleViewModel, ArticleViewModel>(newModel);

                ModelState.Clear();

                return View("~/Views/Article/Article.ascx", newModel);
            }

            return JsonMessage(s);

        }

        /////// <summary>
        /////// return Article content ascx
        /////// </summary>
        /////// <param name="articleId"></param>
        /////// <returns></returns>
        ////public ActionResult AddArticleContent(int articleId)
        ////{


        ////    return View("~/Views/Article/ArticleContent.ascx");
        ////}


        /// <summary>
        /// Move an Article 
        /// </summary>
        /// <param name="articleId"></param>
        /// <param name="newStartPage"></param>
        /// <returns></returns>

         [AjaxAuthorize(Roles = RoleConstant.All)]
        public ActionResult MoveArticle(int articleId, int? newStartPage)
        {

            if (CommonSession.IsUserGraphicsDesigner.Equals(true)) 
            {
                return JsonMessage(false.ToString());
            }

            var article = ArticleManager.GetArticleById(articleId);

            if (CommonSession.IsUserJournalist.Equals(true)) 
            {
                if (article.IsReadyForEditor.Equals(true) || article.IsReadyForGraphic.Equals(true)) 
                {
                    return JsonMessage(false.ToString());
                }
            }

            var newArticle = new Core.Entity.Article();
            article.CopyPropertyValue<Core.Entity.Article, Core.Entity.Article>(newArticle);

            var originalStartpage = article.StartPage;
            var originalEndPge = article.EndPage;

            article.StartPage = newStartPage;

            var result = ArticleManager.IsAppropiatePositionFound(article);

            if (!(result)) 
            {
                article.StartPage = originalStartpage;
                article.EndPage = originalEndPge;
                return JsonMessage(result.ToString());
            }
            ArticleManager.Save(article);

            //newArticle.StartPage = newStartPage == 0 ? null : newStartPage;
            //var isValid = ArticleManager.Validate(newArticle);
            //if (!isValid)
            //{
            //    //article.StartPage = originalStartpage==0?null:originalStartpage; // needed for automatic flush problem of sesssion manager.. neet to fix later
            //    //article.EndPage = originalEndPge;
            //    //return JavaScript("alert('" + isValid.ToString() + "');");
            //    return JsonMessage(isValid.ToString());

            //}
            //else
            //{



            //    article.StartPage = newArticle.StartPage;
            //    article.EndPage = newArticle.EndPage;

            //    // Atomaticaly flush the change the to the database during end_reguest.should call the save function later.
            //    return RedirectToAction("Index", "Storyboard",
            //                            new { publicationId = article.PublicationId });
            //}



            return RedirectToAction("Index", "Storyboard",
                                      new { publicationId = article.PublicationId });
        }
         ///<summary>
         /// Layout overview action for showing the publication 
         /// PDF file are find from the configured folder with Publication_(publicationId).pdf format.
         ///</summary>
         ///<param name="model"></param>
         ///<param name="publicationId"></param>
         ///<returns></returns>
         [AjaxAuthorize(Roles = RoleConstant.All)]
        public ActionResult ShowLayout(StoryboardViewModel model, int publicationId)
        {
            model.Publication = PublicationManager.GetPublicationById(publicationId);
            var publicationLayoutFolder = ArticleContentModel.GetPublicationLayoutFolder(publicationId);
            model.HasLayoutPdf = false;
            if (Directory.Exists(publicationLayoutFolder))
            {
                var publicationPdfFile = Path.Combine(publicationLayoutFolder, "Publication_" + publicationId.ToString() + ".pdf");
                if (System.IO.File.Exists(publicationPdfFile))
                {   
                    model.HasLayoutPdf = true;
                  
                }
                else
                {
                    string[] fileEntries = Directory.GetFiles(publicationLayoutFolder);
                    if (fileEntries.Any(file => !String.IsNullOrEmpty(Path.GetExtension(file)) && Path.GetExtension(file) == ".pdf"))
                    {
                        model.HasLayoutPdf = true;
                    }
                }
            }
            return View("~/Views/Storyboard/LayoutOverview.ascx", model);
        }
         [AjaxAuthorize(Roles = RoleConstant.All)]
        public ActionResult ShowPublicationPdf(StoryboardViewModel model, int publicationId)
        {
            model.Publication = PublicationManager.GetPublicationById(publicationId);
            var publicationLayoutFolder = ArticleContentModel.GetPublicationLayoutFolder(publicationId);
            byte[] PdfData = null;
            if (Directory.Exists(publicationLayoutFolder))
            {
                var publicationPdfFile = Path.Combine(publicationLayoutFolder, "Publication_" + publicationId.ToString() + ".pdf");
                if (System.IO.File.Exists(publicationPdfFile))
                {

                    PdfData = GetPdfData(publicationPdfFile);
                }
                else
                {
                    string[] fileEntries = Directory.GetFiles(publicationLayoutFolder);
                    // show first pdf
                    foreach (var file in fileEntries)
                    {
                        if (!String.IsNullOrEmpty(Path.GetExtension(file)) && Path.GetExtension(file) == ".pdf")
                        {
                            publicationPdfFile = Path.Combine(publicationLayoutFolder, Path.GetFileName(file));
                            PdfData = GetPdfData(publicationPdfFile);
                            break;

                        }
                    }       
                }
            }
            return new PdfActionResult { PdfStream = PdfData };
        }

        private byte[] GetPdfData(string publicationPdfFile)
        {
            byte[] PdfData;
            FileStream objFileStream = new FileStream(publicationPdfFile, FileMode.Open, FileAccess.Read);
            PdfData = new byte[objFileStream.Length];
            objFileStream.Read(PdfData, 0, System.Convert.ToInt32(objFileStream.Length));
            objFileStream.Close();
            objFileStream.Dispose();
            return PdfData;
        }
    }
}
